﻿using DotNetCore.CAP.Messages;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DotNetCore.CAP.MQTT;
using System.Reflection;
using Microsoft.OpenApi.Models;
using System.IO;
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Builder;

namespace Sample.MQTT
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            var cb = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json");
            IConfiguration configuration = cb.Build();
            var loggerFactory = LoggerFactory.Create(builder =>
            {
                builder.AddConsole(); // 控制台日志（所有平台支持）
                builder.AddDebug();   // 调试日志
                                      // 其他日志提供器
            });

            //builder.Services.AddDbContext<AppDbContext>(option => option.UseMySQL(configuration["MySql:ConnectionString"])); //Options, If you are using EF as the ORM
            // Add services to the container.
            services.AddCap(x =>
            {
                x.UseInMemoryStorage();
                //x.UseEntityFramework<AppDbContext>();
                if (configuration["MQTT:Host"] != null)
                {
                    x.UseMQTT(options =>
                    {
                        options.Server = configuration["MQTT:Host"]!;
                        options.Port = Convert.ToInt32(configuration["MQTT:Port"]);
                        options.UserName = configuration["MQTT:UserName"]!;
                        options.Password = configuration["MQTT:Password"]!;
                        options.ClientId = configuration["MQTT:ClientId"]!;
                        options.UseString = Convert.ToBoolean(configuration["MQTT:UseString"]);
                    });
                }
#if NET8_0_OR_GREATER
                x.UseDashboard();
#endif
                x.FailedRetryCount = 5;
                x.FailedThresholdCallback = failed =>
                {
                    var logger = failed.ServiceProvider.GetService<ILogger<Startup>>();
                    logger.LogError($@"A message of type {failed.MessageType} failed after executing {x.FailedRetryCount} several times, 
                            requiring manual troubleshooting. Message name: {failed.Message.GetName()}");
                };
            });
            // 配置 Swagger
            services.AddSwaggerGen(options =>
            {
                var name = Assembly.GetExecutingAssembly().GetName();
                options.SwaggerDoc("v1", new OpenApiInfo { Title = $"{name.Name} API", Version = "v1" });

                // 1. 包含宿主项目自身的 XML 注释（可选）
                var hostXmlFile = $"{name.Name}.xml";
                var hostXmlPath = Path.Combine(AppContext.BaseDirectory, hostXmlFile);
                if (File.Exists(hostXmlPath))
                    options.IncludeXmlComments(hostXmlPath);

                // 2. 包含 .NET Standard 2.0 类库的 XML 注释（关键步骤）
                //var libraryXmlFile = "MyStandardLibrary.xml"; // 类库的 XML 文件名
                //var libraryXmlPath = Path.Combine(AppContext.BaseDirectory, libraryXmlFile);
                //if (File.Exists(libraryXmlPath))
                //    options.IncludeXmlComments(libraryXmlPath);
            });
            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app)
        {
            // 启用 Swagger 中间件
            //if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API v1"));
            }
            app.UseRouting();
            
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
